package com.gxuwz.security;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.gxuwz.business.entity.SysUser;
import com.gxuwz.business.service.ISysUserService;

/**
 * 登录验证
 * <p>
 * 功能描述：处理用户登录
 * 注意：如果登录表单的输入框名字不是username和password，需要在配置文件注入相应的名字
 * 
 * @author Timo
 * @date:2018年5月20日
 */
public class MyUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
	@Autowired
	private ISysUserService userService;
	private static final org.slf4j.Logger logger = LoggerFactory.getLogger("MyUsernamePasswordAuthenticationFilter");
	/**
	 * 重写父类的认证方法
	 */
	public Authentication attemptAuthentication(HttpServletRequest request,HttpServletResponse response) throws AuthenticationException {
		//必须post提交表单，否则抛出异常
		/*if (!request.getMethod().equals("POST")) {
			throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
		}*/
		HttpSession session = request.getSession(false);
		/*@SuppressWarnings("unchecked")
		List<String> authName = (List<String>)session.getAttribute("listRightId");
		if( authName==null || authName.isEmpty()){
			log.error("操作有误！\n请检查以下原因：\n1、用户以匿名方式访问了主页；2、用户名或密码错误；3、该用户未获得任何权限");
			throw new AuthenticationServiceException("用户名或密码错误，或者该用户未拥有任何权限");
		}*/
		SysUser user = (SysUser)session.getAttribute("user");
		if(null == user){
			throw new UsernameNotFoundException("用户未登录");
		}
		String userId = user.getUserName();
		String password = user.getUserPassword();
		logger.info(user.getUserName()+" 登录成功");
		//由于登录是有struts2处理的，这里将正确的用户名和密码放到认证令牌里，待下一步认证
		UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(userId, password);
		
		//允许子类设置详细属性
		setDetails(request, authRequest);
		
		// 运行UserDetailsService的loadUserByUsername 再次封装Authentication
		//通过AuthenticationManager:ProviderManager完成认证任务
		return this.getAuthenticationManager().authenticate(authRequest);
	}

	public ISysUserService getUserService() {
		return userService;
	}

	public void setUserService(ISysUserService userService) {
		this.userService = userService;
	}
	
	public String obtainobtainUsername(){
		return "userName";
	}
	
}
